<template>
  <el-row style="height:100%">
    <page report="true">
      <div class="page-content report-con">
        <div class="reportthead">
          <div class="head-row">
            <span class="choice-title">所属企业：</span>
            <el-cascader
              v-model="company_id_arr"
              :placeholder="'选择所属企业'"
              collapse-tags
              :options="optionsCom"
              ref="cascaderRef"
              :props="{
               expandTrigger: 'hover',
               multiple: 'true',
              }"
              @visible-change="companyVisibleChange"
              size="small"
              style="width:450px">
            </el-cascader>
          </div>
          <div class="head-row">
            <span class="choice-title">所属案场：</span>
            <el-select v-model="case_id"  @change="caseChange" filterable
                       size="small" placeholder="请选择案场" style="width:450px;">
              <el-option
                v-for="item in optionsCase"
                :key="item.id"
                :label="item.case_name"
                :value="item.id">
              </el-option>
            </el-select>
          </div>
          <div class="head-row" id="areaSelect">
            <span class="choice-title">店铺选择：</span>
            <el-select v-model="area_id" @change="areaChange" filterable ref="areaRef"
                       size="small" placeholder="请选择店铺"  style="width:450px" >
              <el-option
                v-for="item in optionsArea"
                :key="item.area_id"
                :label="item.area_name"
                :value="item.area_id">
              </el-option>
            </el-select>
          </div>
          <div class="head-row" style="height: auto; min-height: 36px;">
            <div class="datecheck">
              <span>日期选择：</span>
              <el-date-picker
                v-model="datetimeval.day"
                @change="dataIsChange = true"
                type="daterange"
                align="right"
                unlink-panels
                popper-class="report-date"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                value-format="yyyy-MM-dd"
                format="yyyy-MM-dd"
                :picker-options="pickerOptions">
              </el-date-picker>
              <span style="margin-left: 23px;">时段选择：</span>
              <template>
                <el-time-picker
                  is-range
                  v-model="datetimeval.hm"
                  @change="dataIsChange = true"
                  value-format="HH:mm"
                  format="HH:mm"
                  range-separator="至"
                  start-placeholder="开始时间"
                  end-placeholder="结束时间"
                  placeholder="选择时间范围">
                </el-time-picker>
              </template>
              <el-select v-model="TimeFast" placeholder="快速选择"  @change="TimaFastChange" class="timefast">
                <el-option
                  v-for="item in TimeFastList"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value">
                </el-option>
              </el-select>
            </div>
          </div>
          <div class="head-row ok">
            <el-button @click="updata" class="queryReport"
                       :type="dataIsChange ? 'primary':'success'" size="small">
              <span v-if="dataIsChange"><i class="el-icon-search"></i> 查询数据</span>
              <span v-else><i class="el-icon-refresh-left"></i> 刷新数据</span>
            </el-button>
          </div>
        </div>
        <div class="hei13"></div>
        <div class="card loadingClass" style="height: 690px;"
             v-loading="xxloading"
             element-loading-text="请点击查询报表获取相关数据"
             element-loading-spinner="el-icon-caret-top"
             element-loading-background="rgba(245, 248, 254, 1)" >
          <el-tabs v-model="indicator_key" type="card" @tab-click="updata">
            <el-tab-pane v-for="item in indicator_keys" :label="item.name" :key="item.key" :name="item.key">
              <el-checkbox-group
                v-model="sex"
                :min="1"
                @change="updata"
                style="display: inline-block ; margin:0px 50px">
                <el-checkbox label="1">男性</el-checkbox>
                <el-checkbox label="0">女性</el-checkbox>
              </el-checkbox-group>
              <el-checkbox-group
                v-model="age_group"
                :min="1"
                @change="updata"
                style="display: inline-block;margin: 20px">
                <el-checkbox v-for="item in ageList" :label="item.key" :key="item.key">{{item.info}}</el-checkbox>
              </el-checkbox-group>
              <reportSankey :con_w="con_w" :ref="item.key + 'sankey'" :ageList="ageList">
              </reportSankey>
            </el-tab-pane>
          </el-tabs>
        </div>
        <div class="hei13"></div>
        <reporttable v-show="isShowTable" :tableData = tableData :tableTitle = tableTitle></reporttable>
      </div>
    </page>
  </el-row>
</template>
<style lang="scss">
  .loadingClass{
    .el-loading-mask{
      .el-loading-spinner{
        top: 80px;
        i{
          display: none;
        }
        .el-loading-text{
          font-size: 18px;
          font-weight: bold;
          color:#b4b6bd;
        }
      }

    }
  }
  .card{
    width: 100%;
    background: #fff;
    padding: 15px 10px;
    overflow: hidden;

  }
  .reportthead {
    width: 100%;
    background: #fff;
    padding: 27px 0 20px 45px;
    .head-row {
      line-height: 36px;
      height: 36px;
      margin-bottom: 15px;

      &.ok {
        height: auto;
        min-height: 36px;
        line-height: 36px;
        text-align: center;

        .el-radio-group {
          height: 36px;
          line-height: 36px;

          .el-radio-button__inner {
            height: 36px;
            line-height: 36px;
            padding: 0;
            width: 50px;
            font-size: 12px;
          }
        }

        .queryReport {
          line-height: 36px;
          height: 36px;
          padding: 0 10px;
          margin-right: 45px;
          vertical-align: middle;
          display: inline-block;
          // background-color: #8EC5FC;
          // background-image: linear-gradient(62deg, #8EC5FC 0%, #E0C3FC 100%);
          // border-color: #8EC5FC;
          background: #545deb;
          border-color: #545deb;

          &.el-button--success {
            background: #85ce61;
            border-color: #85ce61;
          }

          span {
            color: #fff;
          }
        }
      }
    }
  }
</style>
<script>
  let moment = require("moment");
  import page from "@/components/page/page";
  import reportGlobal from "@/components/global/reportGlobal";//公共配置
  import reportSankey from "@/components/analyzeReport/reportpublic/reportSankey";
  import reporttable from "@/components/analyzeReport/reportpublic/reportSankeyTable";
  export default {
    data() {
      return {
        code: this.$route.query.code,        //通过菜单栏点击传过来的code判断使用的公共参数
        optionsCom:[],//企业树
        company_id:null,
        company_id_arr:[],
        case_id:null,
        optionsCase:[],
        area_id:null,
        optionsArea:[],
        global:{},
        datetimeval:{
          day:[moment(new Date()).format("YYYY-MM-DD"),moment(new Date()).format("YYYY-MM-DD")],
          hm:['00:00','23:59']
        },
        pickerOptions: {                //时间日期控件规则
          disabledDate(time) {
            return time.getTime() > Date.now() - 8.64e6;   //正常 今天之前
            //  let curDate = (new Date()).getTime();
            //   let three = 14 * 24 * 3600 * 1000;
            //   let threeMonths = curDate - three;
            //   return time.getTime() > Date.now() || time.getTime() < threeMonths;
          },
          shortcuts: [
            {
              text: "今天",
              onClick(picker) {
                const start = moment().format("YYYY-MM-DD");
                const end = moment().format("YYYY-MM-DD");
                picker.$emit("pick", [start, end]);
              }
            },
            {
              text: "昨天",
              onClick(picker) {
                const start = moment()
                .subtract(1, "days")
                .format("YYYY-MM-DD");
                const end = moment()
                .subtract(1, "days")
                .format("YYYY-MM-DD");
                picker.$emit("pick", [start, end]);
              }
            },
            {
              text: "前天",
              onClick(picker) {
                const start = moment()
                .subtract(2, "days")
                .format("YYYY-MM-DD");
                const end = moment()
                .subtract(2, "days")
                .format("YYYY-MM-DD");
                picker.$emit("pick", [start, end]);
              }
            },
            {
              text: "上周同日",
              onClick(picker) {
                const start = moment()
                .subtract(1, "weeks")
                .format("YYYY-MM-DD");
                const end = moment()
                .subtract(1, "weeks")
                .format("YYYY-MM-DD");
                picker.$emit("pick", [start, end]);
              }
            },
            {
              text: "上月同日",
              onClick(picker) {
                const start = moment()
                .subtract(1, "months")
                .format("YYYY-MM-DD");
                const end = moment()
                .subtract(1, "months")
                .format("YYYY-MM-DD");
                picker.$emit("pick", [start, end]);
              }
            },
            {
              text: "本周",
              onClick(picker) {
                const weekOfday = moment().format("E"); //计算今天是这周第几天
                const start = moment()
                .subtract(weekOfday - 1, "days")
                .format("YYYY-MM-DD");
                const end = moment().format("YYYY-MM-DD");
                picker.$emit("pick", [start, end]);
              }
            },
            {
              text: "上一周",
              onClick(picker) {
                const start = moment()
                .week(moment().week() - 1)
                .startOf("week")
                .subtract(-1, "days")
                .format("YYYY-MM-DD");
                const end = moment()
                .week(moment().week() - 1)
                .endOf("week")
                .subtract(-1, "days")
                .format("YYYY-MM-DD");
                picker.$emit("pick", [start, end]);
              }
            },
            {
              text: "本月",
              onClick(picker) {
                const start = moment().month(moment().month()).startOf("month").format("YYYY-MM-DD");
                const end = moment().format("YYYY-MM-DD");
                picker.$emit("pick", [start, end]);
              }
            },
            {
              text: "上一月",
              onClick(picker) {
                const start = moment()
                .month(moment().month() - 1)
                .startOf("month")
                .format("YYYY-MM-DD");
                const end = moment()
                .month(moment().month() - 1)
                .endOf("month")
                .format("YYYY-MM-DD");
                picker.$emit("pick", [start, end]);
              }
            },
            {
              text: "本年度",
              onClick(picker) {
                const start = moment()
                .year(moment().year())
                .startOf("year")
                .format("YYYY-MM-DD");
                const end = moment().format("YYYY-MM-DD");
                picker.$emit("pick", [start, end]);
              }
            },
            {
              text: "上一年",
              onClick(picker) {
                const start = moment()
                .year(moment().year() - 1)
                .startOf("year")
                .format("YYYY-MM-DD");
                const end = moment()
                .year(moment().year() - 1)
                .endOf("year")
                .format("YYYY-MM-DD");
                picker.$emit("pick", [start, end]);
              }
            },
          ],
        },
        TimeFast:'',          //时间快速选择
        TimeFastList:[         //时间快速选择列表
          { label:'最近30分钟',value:'min30' },
          { label:'最近1小时',value:'hour1' },
          { label:'最近2小时',value:'hour2' },
          { label:'全天',value:'today' },
        ],
        dataIsChange:true,

        xxloading:true,//提示信息遮罩层
        con_w:'',//组件宽度
        indicator_key:null,//
        indicator_keys:[],//当前指标
        globalIndicator_keys:[],//本地指标数组
        sex:['0','1'],//性别选择
        ageList:[],//获取年龄组
        age_group:[],//年龄组
        tags:'',
        isShowTable:false,//是否显示表格
        tableData:[{formTarget : ''}],
        tableTitle:'',
      }
    },
    components:{
      page,
      reportSankey,
      reporttable
    },
    created(){
      //根据code来获取公共参数
      for (let i in reportGlobal.queryList) {
        if (this.code == reportGlobal.queryList[i].code) {
          this.global = reportGlobal.queryList[i]
        }
      }
      this.globalIndicator_keys = this.global.indicator_keys
      this.tags = this.global.tags.join(',')
      this.getReady()

    },
    mounted(){
      //初始化触发事件
      setTimeout(() => {
        this.loadEchartResize();
      }, 200)
      //窗口变化触发事件
      setTimeout(() => {
        window.onresize = () => {
          this.loadEchartResize();
        };
      }, 200);
    },
    methods:{
      //获取年龄组配置
      getAgeList(){
        let p = new Promise((res,rej)=>{
          let url = '/sys/face_report/age_group'
          this.$api.post(url)
          .then(data=>{
            // console.log(data);
            this.ageList = data.data;
            this.age_group = this.ageList.map(x=>{
              return x.key
            })
            res()
          })
          .catch(err=>{
             console.log(err);
            this.$message.error('获取年龄组失败')
            this.$Bus.$emit('Loading', false)
            rej()
          })
        })
        return p
      },
      getReady(){
        let _this = this;

        async function ready() {
          await _this.getAgeList()
          await _this.getCompany()
          await _this.getCase()
          await _this.getArea()
        }

        ready().then(data=>{
          this.dataIsChange=true;
        })
        .catch(err=>{
          console.log(err);
          this.$message.warning(err);
        })

        this.$Bus.$emit('Loading',false);
      },
      //获取企业树
      getCompany(){
        let p = new Promise((res,rej)=>{
          let url = '/sys/report_assist_new/company_tree';
          this.$api.get(url)
          .then(data => {
            if(data){
              recursion(data.data);
              function recursion(val) {
                if(val.length){
                  for(let i in val){
                    val[i].value = val[i].id;
                    val[i].label = val[i].company_name;
                    val[i].parent_id_str = val[i].parent_name_list ? val[i].parent_name_list.join('/') : '';
                    if(val[i].children && val[i].children.length){
                      recursion(val[i].children)
                    }else{
                      delete val[i].children
                    }
                  }
                }
              }
              this.$nextTick(()=>{
                let arr = [];
                recursionData(Array.of(data.data[0]))
                function recursionData(val) {
                  if(val.length){
                    for(let i in val){
                      if(val[i].children){
                        recursionData(val[i].children)
                      }else{
                        arr.push(val[i].node_location.split('-').slice(0,-1))
                        delete val[i].children
                      }
                    }
                  }
                }
                this.optionsCom = data.data;
                let company_id_arr = [];//配置当前第一个选中的值
                arr.map(x=>{
                  for(let i = 0 ; i < x.length;i++){
                    if(x[i] == data.data[0].id){
                      company_id_arr.push(x.slice(i,x.length))
                    }
                  }
                });
                this.company_id_arr = company_id_arr;
                this.company_id = company_id_arr.join(',');
                res();
              })
            }
          })
          .catch(err=>{
            this.optionsCom = [];
            this.optionsCase = [];
            this.optionsArea = [];
            this.company_id_arr = [];
            this.company_id = null;
            this.case_id = null;
            this.area_id = null;
            rej('未获取到企业树')
          })
        })
        return p
      },
      //获取案场
      getCase(){
        let p = new Promise((res,rej)=>{
          let lsarr=[];
          let company_id_arr = this.company_id_arr
          for(let i in company_id_arr) {
            lsarr.push(company_id_arr[i][company_id_arr[i].length-1])
          }
          let params={
            org_id_list:lsarr,
            org_type:1
          }
          let url='/sys/report_assist_new/case_list?tags='+this.global.tags;
          this.$api.post(url,params)
          .then(data=>{
            this.optionsCase = [];
            if(data.data && data.data.length){
              this.optionsCase = data.data;
              this.case_id = data.data[0].id;
              res();
            } else{
              this.optionsCase = [];
              this.optionsArea = [];
              this.case_id = null;
              this.area_id = null;
              rej('该企业下无案场')
            }
          })
          .catch(err=>{
            this.optionsCase = [];
            this.optionsArea = [];
            this.case_id = null;
            this.area_id = null;
            rej('该企业下无案场')
          })
        })
        return p
      },
      //获取店铺
      getArea(){
        let p = new Promise((res,rej)=>{
          //初始化设置区域多选
          let params={
            org_id_list:Array.of(this.case_id),
            org_type:2
          }
          let url='/sys/report_assist_new/find_area?tags='+ this.global.tags.join(',')
          this.$api.post(url,params)
          .then(data=>{
            this.optionsArea = [];
            this.area_id = [];
            if(data.data){
              if(data.data.length){
                this.optionsArea = data.data.map(x=>{
                  if(x.tags && x.tags.includes(-1)) {
                    x.area_name = '[排除]'+ x.area_name
                  }
                  return x
                })
                //默认全选状态
                this.area_id = this.optionsArea[0].area_id;
                this.$nextTick(()=>{
                  this.changeBgColor()
                });
              }
            }
            res()
          })
          .catch(err=>{
            this.optionsArea = [];
            this.area_id = null;
            rej('该案场下无店铺')
          })
        })
        return p
      },

      changeBgColor(){
        if(this.$refs.areaRef.query.includes('[排除]')){
          $('#areaSelect').find('.el-input__inner').css({color:'#f56c6c'})
        }else{
          $('#areaSelect').find('.el-input__inner').css({color:'#777'})
        }
      },

      companyVisibleChange(val){
        if(!val){
          this.companyChange();
        }
      },
      //企业选择改变
      companyChange(){
        let _this = this
        if(!this.company_id_arr.length){
          this.$message.warning('请至少选择一个企业');
          this.optionsCase=[];
          this.case_id='';
          this.optionsArea=[];
          this.area_id='';
          if(!this.xxloading){
            this.removedata(true)
          }
          return
        }
        this.$Bus.$emit('Loading',true);
        let company_id_arr = this.company_id_arr.map(x => {
          return x.slice(-1)[0]
        });
        this.company_id = company_id_arr.join(',')
        async function companyChange() {
          await _this.getCase()
          await _this.getArea()
        }
        companyChange().then(data=>{
          this.dataIsChange=true;
        })
        .catch(err=>{
          console.log(err);
          this.$message.warning(err);
        })
        this.$Bus.$emit('Loading',false);
      },

      caseChange(val){
        if (this.case_id == null) {
          this.$message.warning('请至少选择一个案场');
          return
        }
        this.getArea().then(data=>{
          this.dataIsChange=true;
        })
        .catch(err=>{
          this.$message.warning(err);
        });
        this.$Bus.$emit('Loading',false);
      },
      areaChange(){
        if (this.area_id == null) {
          this.$message.warning('请至少选择一个店铺');
          return
        }
        this.dataIsChange=true;
        this.$nextTick(()=>{
          this.changeBgColor()
        });
      },
      //快速选择时段
      TimaFastChange(val){
        switch (val) {
          case "min30": {
            let str_hm = moment().subtract(30, 'minutes').format('HH:mm');
            let end_hm = moment().format('HH:mm');
            this.datetimeval.hm = [str_hm, end_hm];
            break;
          }
          case "hour1": {
            let str_hm = moment().subtract(1, 'hours').format('HH:mm');
            let end_hm = moment().format('HH:mm');
            this.datetimeval.hm = [str_hm, end_hm];
            break;
          }
          case "hour2": {
            let str_hm = moment().subtract(2, 'hours').format('HH:mm');
            let end_hm = moment().format('HH:mm');
            this.datetimeval.hm = [str_hm, end_hm];
            break;
          }
          case "today": {
            this.datetimeval.hm = ["00:00", "23:59"];
            break;
          }
        }
        this.dataIsChange=true;
      },
      //条件查询
      updata(){
        if(!this.company_id_arr.length) {
          this.$message.warning('请至少选择一个企业');
          return
        }
        if(!this.case_id){
          this.$message.warning('请选择案场');
          return
        }
        if(!this.area_id){
          this.$message.warning('请选择店铺');
          return
        }
        if(!this.datetimeval.day){
          this.$message.warning('请选择日期');
          return
        }
        if(!this.datetimeval.hm){
          this.$message.warning('请选择时段');
          return
        }
        this.$Bus.$emit('Loading', true)
        this.xxloading = false;
        this.isShowTable = true;
        this.dataIsChange=false;
        this.getKpi().then(()=>{
          let url = '/sys/face_report/area_diversion?area_id='+ this.area_id + '&tags=' + this.tags +
            '&indicator_key='+ this.indicator_key + '&sex=' + this.sex.join(',') + '&age_group='+ this.age_group.join(',') +
            '&start_day=' + this.datetimeval.day[0] + '&end_day=' + this.datetimeval.day[1] +
            '&start_hm=' + this.datetimeval.hm[0] +'&end_hm=' + this.datetimeval.hm[1]
          this.$api.post(url)
          .then(data=>{
            if(data.data){
              let formList = data.data.form_list ? data.data.form_list : []
              let toList = data.data.to_list ? data.data.to_list : []
              this.tableTitle = `${this.$refs.areaRef.query}-${reportGlobal.name[this.indicator_key]}-${this.datetimeval.day[0]}-${this.datetimeval.hm[0]}至
            ${this.datetimeval.day[1]}-${this.datetimeval.hm[1]} 导流数据`

              if(formList.length == 0 && toList.length == 0){
                this.$message.warning('暂无数据');
                this.$refs[this.indicator_key + 'sankey'][0].upData(false)
                this.tableData = [];
                this.tableTitle = ''
                return
              }
              this.getTableData(formList,toList);
              this.$refs[this.indicator_key + 'sankey'][0].upData(formList,toList,this.$refs.areaRef.query,reportGlobal.name[this.indicator_key])
            }else{
              this.$message.warning('暂无数据');
              this.$refs[this.indicator_key + 'sankey'][0].upData(false)
              this.tableData = [];
              this.tableTitle = ''
              return
            }

          })
          .catch(err=>{
            console.log(err);
          })
        })
        .catch(err=>{
          this.$message.error(err)
        })

        this.$Bus.$emit('Loading', false)

      },
      //获取权限下的指标
      getKpi(){
        let p = new Promise((res,rej)=>{
          let url = '/sys/report_assist_new/get_indicator_list'
          let params = {
            org_id_list : Array.of(this.area_id),
            org_type : 3,
          }
          this.$api.post(url,params)
          .then(data=>{
            console.log(data,'getkpi');
            this.indicator_keys = data.data.filter(x => {
              return this.globalIndicator_keys.includes(x.key)
            })
            if(this.indicator_key == 0 || !this.indicator_key){
              this.indicator_key = this.indicator_keys[0].key
            }
            this.$nextTick(()=>{
              res()
            })
          })
          .catch(err=>{
            rej(err)
          })
        })
        return p
      },

      getTableData(formList,toList){
        formList = formList.sort((x,y)=>{
          if(x.value > y.value){
            return -1
          }else{
            return 1
          }
        })
        toList = toList.sort((x,y)=>{
          if(x.value > y.value){
            return -1
          }else{
            return 1
          }
        })
        let length = formList.length > toList.length ? formList.length : toList.length
        let tableData = [];
        for (let i = 0; i < length; i++) {
          let obj = {}
          obj.formSource = formList[i] ? formList[i].source_name : ''
          obj.formTarget = formList[i] ? formList[i].target_name : ''
          obj.formValue = formList[i] ? formList[i].value : ''
          obj.toSource = toList[i] ? toList[i].source_name : ''
          obj.toTarget = toList[i] ? toList[i].target_name : ''
          obj.toValue = toList[i] ? toList[i].value : ''
          tableData.push(obj)
        }
        this.tableData = tableData
      },
      //清除数据
      removedata(iscomp=false) {
        this.$refs[this.indicator_key + 'sankey'][0].upData(false);
        this.tableData = [];
        this.tableTitle = ''
        this.commonData = null;
        if(iscomp) this.DataV = {};
      },
      loadEchartResize(){
        this.con_w = $(".page-content").width()
      },
    }
  }
</script>

<style>
</style>